<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :width="width"
    :before-close="handleClose"
    :close-on-click-modal="closeOnClickModal"
  >
    <slot></slot>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel" :disabled="confirmLoading">{{ cancelText }}</el-button>
      <el-button 
        type="primary" 
        @click="handleConfirm" 
        :loading="confirmLoading"
        :disabled="confirmDisabled"
      >
        {{ confirmText }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'FormDialog',
  props: {
    title: {
      type: String,
      default: '提示'
    },
    width: {
      type: String,
      default: '50%'
    },
    confirmText: {
      type: String,
      default: '确定'
    },
    cancelText: {
      type: String,
      default: '取消'
    },
    closeOnClickModal: {
      type: Boolean,
      default: false
    },
    confirmDisabled: {
      type: Boolean,
      default: false
    },
    beforeClose: Function
  },
  data() {
    return {
      confirmLoading: false,
      visible: true,
    }
  },
  methods: {
    handleClose(done) {
      if (this.beforeClose) {
        this.beforeClose(done)
      } else {
        this.handleCancel()
      }
    },
    handleCancel() {
      this.$emit('cancle')
      setTimeout(() => {
        this.visible = false
      }, 200)
    },

    handleConfirm() {
      this.visible = false;
      this.confirmLoading = true
      try {
        this.$emit('confirm');
      } finally {
        this.confirmLoading = false
      }
    }
  }
}
</script>